<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 控制面板，基类
 * @author Tujt 2017-10-11
 */
class Manage extends My_Controller
{
	private $module = 'Manage';//当前模块
    private $assign = array();
    /**
     * 默认方法
     * @author Toby.tu 2017-10-11
     */
    public function init(){
		//初始化model
        $this->vendor('models/'.$this->module.'_model','model');
    }
    /**
     * 用户列表
     * @author Toby.tu 2016-08-30
     */
    public function index(){
        $input = $this->input->post();
        $cur_page = 1;
        if(isset($input['cur_page'])){
            $cur_page = $input['cur_page'];
        }
        $search = array();
        $filter = array(
            'name','status','category_first','category_parent','category_id'
        );
        foreach ($filter as $fld) {
            if(isset($input[$fld]) && trim($input[$fld]) != ''){
                $search[$fld] = $input[$fld];
            }
        }
        $brand_id = 0;
        if(isset($input['brand_id']) && $input['brand_id'] > 0){
            $brand_id = $input['brand_id'];
        }else if('yes' != $this->assign['is_admin']){//非管理员
            $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            if(empty($brand_id)){
                die('没有品牌权限。');
            }
        }
        if($brand_id > 0) $search['brand_id'] = $brand_id;
        $search['is_admin'] = $this->assign['is_admin'];//是否管理员
        // $this->pagesize = 2;
        $goodsList = $this->goods_model->getGoodsList($search,$cur_page,$this->pagesize);
        $page_count = $this->goods_model->getGoodsCount($search);
        $this->vendor('models/category_model','category_model');
        foreach ($goodsList as $key => &$goodobj) {
            $category = $this->category_model->getOne(['id'=>$goodobj['category_first']]);
            if(!empty($category)){
                $goodobj['category_first_name'] = $category['name'];
            }else{
                $goodobj['category_first_name'] = '';
            }
            $category = $this->category_model->getOne(['id'=>$goodobj['category_parent']]);
            if(!empty($category)){
                $goodobj['category_parent_name'] = $category['name'];
            }else{
                $goodobj['category_parent_name'] = '';
            }
            $category = $this->category_model->getOne(['id'=>$goodobj['category_id']]);
            if(!empty($category)){
                $goodobj['category_id_name'] = $category['name'];
            }else{
                $goodobj['category_id_name'] = '';
            }
        }
        $this->assign['goodsList'] = $goodsList;
        $pagetitle = '';$paginate = '';
        if($page_count > 0){
            $paginate = $this->paginate($cur_page,$page_count);
            $start = (($cur_page - 1) * $this->pagesize ) + 1;
            $end = ($start+$this->pagesize-1);
            if($end > $page_count){
                $end = $page_count;
            }
            $pagetitle = $start.' ~ '.$end;
            $pagetitle .= ' &nbsp;&nbsp;&nbsp;&nbsp;共 '.$page_count.' 条';
        }
        $this->assign['paginate'] = $paginate;
        $this->assign['pagetitle'] = $pagetitle;
        $this->assign['search'] = $search;
        $this->assign['cur_page'] = $cur_page;
        //获取是否管理员选项
        $this->vendor('@.Picklist_model');
        $is_start_opts = $this->picklist_model->getOptsByName('the_shelf');
        $this->assign['is_start_opts'] = $is_start_opts;
        $this->assign['is_start_label'] = current($is_start_opts)['label'];
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        if(isset($input['ajax']) && 1 == $input['ajax']){
            $this->load->view('admin/goods/list',$this->assign);
        }else{
            $this->assign['view'] = 'admin/goods/index';
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 创建页面
     * @author Toby.tu 2016-08-31
     */
    public function create(){
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        $this->assign['session_key'] = '';
        $this->assign['view'] = 'admin/goods/create';
        $this->load->view('admin/common/frame',$this->assign);
    }
    /**
     * 新增权限组
     * @author Toby.tu 2016-08-31
     */
    public function store(){
        try {
            $input = $this->input->post();
            // dd($input);die;
            if(!isset($input['goods'])){
                throw new Exception('参数不正确。');
            }
            if(empty($input['goods']['name'])){
                throw new Exception('请输入商品标题。');
            }
            $brand_id = 0;
            if(isset($input['goods']['brand_id']) && $input['goods']['brand_id'] > 0){
                $brand_id = $input['goods']['brand_id'];
            }else if('yes' != $this->assign['is_admin']){//非管理员
                $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            }
            if(empty($brand_id)){
                throw new Exception('没有对应的品牌，不能保存。');
            }
            $where = ['name'=>$input['goods']['name']];
            $where['brand_id'] = $brand_id;
			$where['delete_id'] = 0;
            $goods = $this->goods_model->getOne($where);
            if(!empty($goods)){
                throw new Exception('商品标题已存在。');
            }
            $param = $input['goods'];
            $param['create_time'] = $this->phpdate->time();
            $param['update_time'] = $param['create_time'];
            $param['create_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            if(!isset($param['sort'])){
                $param['sort'] = 1;
            }
            $param['brand_id'] = $brand_id;
            $mtime = $this->phpdate->mtime();
            $param['code'] = 'G'.date('ymdHis',time()).substr($mtime,-4).rand(1000,9999);//毫秒时间戳加随机数
            $this->goods_model->newData($param);
            redirect('admin/goods/index');die;
        } catch (Exception $e) {
            $this->assign += $input['goods'];
            //获取品牌列表
            if('yes' == $this->assign['is_admin']){
                $this->vendor('@.Brand_model');
                $brands = $this->brand_model->getAll();
                $this->assign['brand_opts'] = $brands;
            }
            $this->assign['error_code'] = $e->getMessage();
            $this->assign['view'] = 'admin/goods/create';
            $mtime = $this->phpdate->mtime();
            $key = 'content_'.date('ymdHis',time()).substr($mtime,-4).rand(1000,9999);
            $_SESSION[$key] = $input['goods']['content'];
            $this->assign['session_key'] = $key;
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 创建页面
     * @author Toby.tu 2016-08-31
     */
    public function edit($id){
        $goods = $this->goods_model->getOne(['id'=>$id]);
        unset($goods['status']);
        $this->assign += $goods;
        $this->assign['id'] = $id;
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        // dd($goods);
        $this->assign['view'] = 'admin/goods/edit';
        $this->load->view('admin/common/frame',$this->assign);
    }
    /**
     * 获取产品内容
     * @author Toby.tu 2017-03-22
     */
    public function postGoodContent($id=0){
        if($id > 0){
            $goods = $this->goods_model->getOne(['id'=>$id]);
            echo $goods['content'];die;
        }else{
            $input = $this->input->post();
            if(isset($_SESSION[$input['session_key']])){
                $content = $_SESSION[$input['session_key']];
                unset($_SESSION[$input['session_key']]);
                echo $content;die;
            }
        }
    }
    /**
     * 新增权限组
     * @author Toby.tu 2016-08-31
     */
    public function update($id){
        try {
            $input = $this->input->post();
            // dd($input);die;
            if(!isset($input['goods'])){
                throw new Exception('参数不正确。');
            }
            if(empty($input['goods']['name'])){
                throw new Exception('请输入商品标题。');
            }
            $brand_id = 0;
            if(isset($input['goods']['brand_id']) && $input['goods']['brand_id'] > 0){
                $brand_id = $input['goods']['brand_id'];
            }else if('yes' != $this->assign['is_admin']){//非管理员
                $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            }
            $where = ['name'=>$input['goods']['name']];
            if($brand_id > 0){
                $where['brand_id'] = $brand_id;
            }
			$where['delete_id'] = 0;
            $goods = $this->goods_model->getOne($where);
            if(!empty($goods) && $id != $goods['id']){
                throw new Exception('商品标题已存在。');
            }
            $param = $input['goods'];
            $param['update_time'] = $this->phpdate->time();
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $this->goods_model->updateById($id,$param);
            redirect('admin/goods/index');die;
        } catch (Exception $e) {
            $this->assign += $input['goods'];
            $this->assign['id'] = $id;
            //获取品牌列表
            if('yes' == $this->assign['is_admin']){
                $this->vendor('@.Brand_model');
                $brands = $this->brand_model->getAll();
                $this->assign['brand_opts'] = $brands;
            }
            $this->assign['error_code'] = $e->getMessage();
            $this->assign['view'] = 'admin/goods/edit';
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 禁用启用
     * @author Toby.tu 2016-08-31
     */
    public function enable($id){
        try {
            $input = $this->input->get();
            if(!isset($input['status'])){
                throw new Exception('参数不正确。');
            }
            $param = array();
            $param['status'] = ($input['status']==1)?0:1;
            $this->goods_model->updateById($id,$param);
            $this->ajaxReturn('SUCCESS');
        } catch (Exception $e) {
            $this->ajaxReturn($e->getMessage(),$e->getCode());
        }
        //     redirect('admin/goods/index');die;
        // } catch (Exception $e) {
        //     redirect('admin/goods/index');die;
        // }
    }
    /**
     * 删除
     * @author Toby.tu 2016-08-31
     */
    public function destroy($id){
        if('yes' != $this->permis_logic->isAdmin()){
            die('不是管理员，不允许执行删除操作。');
        }
        $param = array();
        $current_id = $this->permis_logic->getLoginUserInfo()['id'];
        $param['delete_id'] = $current_id;
        $param['delete_time'] = $this->phpdate->time();
        $this->goods_model->updateById($id,$param);
        redirect('admin/goods/index');die;
    }
    public function upload(){
        $this->load->view('admin/goods/upload',$this->assign);
    }
	public function upload2(){
        $this->load->view('admin/goods/upload2',$this->assign);
    }
	public function upload3(){
        $this->load->view('admin/goods/upload3',$this->assign);
    }
    /**
     * 上传地址
     * @author Toby.tu 2017-03-03
     */
    public function uploadfile(){
        $info = array();
        if (isset($_FILES['uploadFile'])){
            $namearr = explode('.', $_FILES['uploadFile']['name']);
            $mtime = $this->phpdate->mtime();
            $file = date('ymdHis',time()).substr($mtime,-4).rand(1000,9999).'.'.$namearr[1];//毫秒时间戳加随机数
            $path = 'upload/'.$this->phpdate->get('Y/m/d');
            $filepath = config_item('root_path').'/'.$path;
            $this->common->createdir($filepath);
            $config['upload_path']      = $filepath;
            $config['allowed_types']    = '*';
            $config['max_size']         = 1000000;
            $config['file_name']        = $file;

            $this->load->library('upload', $config);

            if($_FILES['uploadFile']['name']){
                $this->load->library('Qiniu');
                $img = $this->qiniu->saveFileByNameAndPath('uploadFile','upload/Product/');
                // $tmp['base_image'] = 'http://phpbasefiles.woaap.com/'.$img['key'];
                $info = array();
                $info['upload_path'] = '';
                $info['upload_file'] = '';
                $info['upload_name'] = $_FILES['uploadFile']['name'];
                $info['upload_type'] = $_FILES['uploadFile']['type'];
                $info['upload_size'] = $_FILES['uploadFile']['size'];
                $info['upload_url'] = 'http://phpbasefiles.woaap.com/'.$img['key'];
                $input = $this->input->post();
                if(isset($input['backurl'])){
                    $this->load->view('admin/goods/'.$input['backurl'],$info);
                }else{
                    $this->load->view('admin/goods/upload',$info);
                }
            }
    //         if ( ! $this->upload->do_upload('uploadFile')){
    //             echo json_encode(array('errorcode' => 1001 , 'errormsg' => $this->upload->display_errors()));
    //         }else{
    //             $info = $this->upload->data();
    //             $info['upload_path'] = $filepath;
    //             $info['upload_file'] = $file;
    //             $info['upload_name'] = $_FILES['uploadFile']['name'];
    //             $info['upload_type'] = $_FILES['uploadFile']['type'];
    //             $info['upload_size'] = $_FILES['uploadFile']['size'];
    //             $info['upload_url'] = base_url().$path.'/'.$file;
				// $input = $this->input->post();
				// if(isset($input['backurl'])){
				// 	$this->load->view('admin/goods/'.$input['backurl'],$info);
				// }else{
				// 	$this->load->view('admin/goods/upload',$info);
				// }
    //         }
        }
    }
    /**
     * 批量上下架
     * @author Toby.tu 2017-03-06
     */
    public function updateStatus(){
        try {
            $input = $this->input->post();
            if(!isset($input['updatestatus']) || !isset($input['goods_id'])){
                throw new Exception('参数不正确。');
            }
            $param = array();
            $param['status'] = $input['updatestatus'];
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['update_time'] = $this->phpdate->time();
            $goods_id_arr = explode(',',$input['goods_id']);
            $this->goods_model->updateInId($goods_id_arr,$param);
            $this->ajaxReturn('SUCCESS');
        } catch (Exception $e) {
            $this->ajaxReturn($e->getMessage(),$e->getCode());
        }
    }
}
